package com.ht.api.db;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import cn.hutool.json.JSONObject;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class DbList extends ArrayList<Entity> implements Serializable {
	private static final long serialVersionUID = 1L;

	private long pagenum;
	private long pagesize;
	private long total;

	private String table;
	private Set<String> fieldNames;

	public DbList() {

	}

	public DbList(String table) {
		this.table = table;
	}

	public static DbList create() {
		return new DbList();
	}

	public static DbList create(String table) {
		return new DbList(table);
	}

	public static DbList create(Entity entity) {
		DbList dbList = new DbList(entity.getTable());
		dbList.add(entity);
		return dbList;
	}

	public static DbList create(List<JSONObject> datalist) {
		return create(datalist, null);
	}

	public static DbList create(List<JSONObject> datalist, String tableName) {
		DbList dblist = new DbList();

		if (datalist.isEmpty()) {
			return dblist;
		}

		for (JSONObject entity : datalist) {
			Entity dbEntity = entity.toBean(Entity.class);
			dbEntity.setTable(tableName);

			for (String field : dbEntity.keySet()) {
				Object object = dbEntity.get(field);
				if (object != null && object.getClass().getSimpleName().equals("Long")) {
					dbEntity.set(field, String.valueOf(object));
				}

				if (field.equals("main_id")) {
					dbEntity.setMainId(dbEntity.getStr(field));
				}
			}

			dblist.add(dbEntity);
		}

		dblist.setFieldNames(datalist.get(0).keySet());

		if (tableName != null) {
			dblist.setTable(tableName);
		}

		return dblist;
	}

	public List<Object> getFieldDataList(String field) {
		return this.stream().map(json -> json.get(field)).collect(Collectors.toList());
	}
}